// 拼接页面数据，通过正则找到{{}}，然后替换内容
function tplReplace(template, templateObject) {
    return template().replace(/\{\{(.*?)\}\}/g, (node, key) => {
        return templateObject[key.trim()]
    })
}

// 回到页面顶部
function scrollToTop() {
    setTimeout(() => {
        window.scrollTo(0, 0)
    }, 0);
}

// 对新闻数据进行切割分页
function setPageData(data, count) {
    // 获取数据来源长度
    const len = data.length;
    let pageData = [];
    let index = 0;
    // 当长度大于index时，不断地分割index到index+要分的长度
    while (index < len) {
        pageData.push(data.slice(index, index += count));
    }
    return pageData;
}

// 页面触底触发
function scrollToBottom(callback) {
    if (_getScrollTop() + _getWindowHeight() === _getScrollHeight()) {
        callback();
    }
}

// 点击元素获取到最外层元素
function getItemNode(target) {
    while (target = target.parentNode) {
        if (target.className.split(' ')[0] === 'news-item') {
            return target;
        }
    }
}

// 传入key获取到当前页面的路径参数的value
function getUrlQueryValue (key) {
  const reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)', 'i');
  const res = window.location.search.substr(1).match(reg);
  return res !== null ? decodeURIComponent(res[2]) : null;
}

export {
    tplReplace,
    scrollToTop,
    setPageData,
    scrollToBottom,
    getItemNode,
    getUrlQueryValue
}

/*********** 内部方法 ************/
function _getScrollTop() {
    var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
    if (document.body) {
        bodyScrollTop = document.body.scrollTop;
    }
    if (document.documentElement) {
        documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
    return scrollTop;
}

function _getScrollHeight() {
    var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
    if (document.body) {
        bodyScrollHeight = document.body.scrollHeight;
    }
    if (document.documentElement) {
        documentScrollHeight = document.documentElement.scrollHeight;
    }
    scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
    return scrollHeight;
}

function _getWindowHeight() {
    var windowHeight = 0;
    if (document.compatMode == "CSS1Compat") {
        windowHeight = document.documentElement.clientHeight;
    } else {
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}